<script setup lang="ts">
import { onMounted } from 'vue';
import { state, filterState } from './state';
import dayjs from 'dayjs';
import { navigateTo, showLoading } from '@tarojs/taro';
import { Search2 as NutIconSearch2 } from '@nutui/icons-vue-taro';
import { APP_PLAN_TASK_LIST_QUERY } from '/@/api/modules/maintain/plan-task';

/**
 * 选择全部
 **/
function allSelected() {
  filterState.startTime = '';
  filterState.endTime = '';
  refreshList();
}

/**
 * 选择时间过滤
 */
function timeSelected() {
  filterState.TimePickerVisible = true;
}

/**
 * @description 跳转到详情页面
 * @param item 点击的item项
 */
function jumpToDetailPage(item: PlanTask.Dto) {
  navigateTo({
    url: `/pages/inspection/detail/index?id=${item.id}&handleStatus=${item.handleStatus}&planBizType=${item.planBizType}`,
  });
}

/**
 *@description 保养计划列表
 * @param page 当前页
 * @param pageSize -每页条数
 */
function queryList(page: number = 1, pageSize: number = 15) {
  if (!page && state.finished) return;
  state.loading = true;

  let handleTimeStart: number = 0;
  let handleTimeEnd: number = 0;
  if (state.activeStatus === 1 && filterState.startTime && filterState.endTime) {
    handleTimeStart = dayjs(filterState.startTime).valueOf() || 0;
    handleTimeEnd = dayjs(filterState.endTime).valueOf() || 0;
  }
  showLoading();
  APP_PLAN_TASK_LIST_QUERY({
    comQuery: { page, pageSize },
    taskCode: state.searchValue,
    planType: 1,
    handleStatus: state.activeStatus,
    handleTimeStart,
    handleTimeEnd,
  })
    .then((res) => {
      state.loading = false;
      if (
        state.activePage >=
        (res.comQuery?.pageCount ||
          (res.comQuery?.totalCount as number) / (res.comQuery?.pageSize as number) ||
          1)
      ) {
        state.finished = true;
      }

      if (filterState.startTime && filterState.endTime) {
        state.statusQuantity.set(
          1,
          `已完成(${res.finishedQuantity > 99 ? '99+' : res.finishedQuantity})`,
        );
      } else {
        state.statusQuantity.set(
          2,
          `未完成(${res.unfinishedQuantity > 99 ? '99+' : res.unfinishedQuantity})`,
        );
        state.statusQuantity.set(
          1,
          `已完成(${res.finishedQuantity > 99 ? '99+' : res.finishedQuantity})`,
        );
      }

      if (!res.planTaskDto || !res.planTaskDto.length) return;
      res.planTaskDto.forEach((item) => state.list.push(item));
      state.activePage += 1;
    })
    .catch(() => {
      state.loading = false;
    });
}

/**
 * @function 加载
 */
function onLoading() {
  if (state.finished) return;
  queryList(state.activePage);
}

/**
 * 关键字搜索回调
 */
function search() {
  refreshList();
}

/**
 * 列表刷新
 */
function refreshList() {
  state.activePage = 1;
  state.loading = true;
  state.finished = false;
  state.list = [];
  onLoading();
}

onMounted(() => {
  refreshList();
});

/**
 * 选择时间区域
 */
function selectedTimeRange(startTime: string, endTime: string) {
  filterState.startTime = startTime;
  filterState.endTime = endTime;
  filterState.TimePickerVisible = false;
  refreshList();
}
</script>

<template>
  <view class="inspection-list app-page--1">
    <app-navbar title="巡检任务" />
    <nut-searchbar
      v-model="state.searchValue"
      @search="search"
      placeholder="输入任务编号、任务名称，查询任务"
      input-background="#EAEBED"
      class="inspection-list__search"
    >
      <template v-slot:leftin>
        <nut-icon-search2 />
      </template>
    </nut-searchbar>
    <nut-tabs
      v-model="state.activeStatus"
      v-if="state.statusQuantity.size > 0"
      @change="refreshList()"
    >
      <nut-tab-pane
        v-for="[key, value] in state.statusQuantity"
        :key="key"
        :title="value"
        :pane-key="key"
      />
    </nut-tabs>
    <scroll-view
      class="app-page__wrapper"
      :scroll-y="true"
      :lower-threshold="100"
      @scrolltolower="onLoading()"
    >
      <view class="inspection-list__wrapper">
        <app-time-range-filter
          v-if="Number(state.activeStatus) === 1"
          :start-time="filterState.startTime"
          :end-time="filterState.endTime"
          @all-selected="allSelected"
          @time-selected="timeSelected"
        />
        <view
          class="inspection-item"
          v-for="item in state.list"
          :key="item.id || ''"
          @click="jumpToDetailPage(item)"
        >
          <view class="inspection-item__header">
            <view class="inspection-item__header--left">
              <text class="inspection-item__title">{{ item.planName || '_' }}</text>
            </view>
            <view class="inspection-item__header--right">
              <text class="inspection-item__remain" v-if="item.handleStatus === 2"
                >剩余:&nbsp;&nbsp;{{ item.validDurationDesc || '_' }}</text
              >
            </view>
          </view>
          <view>
            <text>任务编号:&nbsp;&nbsp;</text>
            <text>{{ item.taskCode || '_' }}</text>
          </view>
          <view>
            <text>任务进度:&nbsp;&nbsp;</text>
            <text>{{ item.deviceHandledCount }}/{{ item.deviceTotal }}</text>
          </view>
          <view v-if="item.handleStatus === 2">
            <text>执行时间:&nbsp;&nbsp;</text>
            <text
              >{{ dayjs(item.validTime).format('YYYY-MM-DD HH:mm') || '_' }}至{{
                dayjs(item.invalidTime).format('YYYY-MM-DD HH:mm') || '_'
              }}</text
            >
          </view>
          <view v-else>
            <text>完成时间:&nbsp;&nbsp;</text>
            <text>{{ dayjs(item.handleTime).format('YYYY-MM-DD HH:mm:ss') }}</text>
          </view>
        </view>
      </view>
      <view class="app-page__list-tips">
        <text v-if="!state.list.length">暂无数据！</text>
        <text v-else-if="state.list.length && state.loading">加载中...</text>
        <text v-else-if="state.list.length && state.finished">加载完成!</text>
      </view>
    </scroll-view>
    <app-time-range-picker-popup
      v-model="filterState.TimePickerVisible"
      @on-selected="selectedTimeRange"
    ></app-time-range-picker-popup>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
